import { InfoCircleFilled } from '@ant-design/icons'
import { App, Button } from 'antd'
import cs from 'classnames'
import { forwardRef, useContext, useImperativeHandle, useState } from 'react'
import { CSSTransition } from 'react-transition-group'

import { GlobalContext } from '@/context'
import useLocale from '@/utils/useLocale'

import Camera from '../Camera'
import locale from './locale'
import styles from './style/index.module.less'

type File = { path: string; name: string }[]

const UploadFile = (
  {
    fileTypes,
    onFile,
  }: { fileTypes?: string[]; onFile?: (file: File, type: string, questionIndex?: number) => void },
  ref
) => {
  const { modal } = App.useApp()
  const { lang } = useContext(GlobalContext)
  const t = useLocale(locale)

  useImperativeHandle(ref, () => ({
    open: open,
    chooseFile: chooseFile,
  }))

  const [type, setType] = useState<string>('')
  const [questionIndex, setQuestionIndex] = useState<number | null>()
  const [show, setShow] = useState<boolean>(false)
  const open = (type: string, questionIndex?: number) => {
    setMode('choose')
    setShow(true)
    setType(type)
    setQuestionIndex(questionIndex)
  }

  const close = () => {
    setShow(false)
  }

  const onSubmit = (paths: File) => {
    if (paths.length > 0) {
      onFile(paths, type, questionIndex)
    }
    setShow(false)
    setMode('choose')
  }

  const [mode, setMode] = useState<'choose' | 'camera'>('choose')

  const chooseFile = () => {
    close()
    const paths = window.electron?.ipcRenderer.chooseFiles((fileTypes = ['jpg', 'png', 'jpeg']))
    if (paths.length > 0) {
      onFile(paths, type, questionIndex)
    }
  }

  const onCamera = async () => {
    const permissions = await window.electron?.ipcRenderer.permissions('camera')
    if (permissions) {
      setMode('camera')
      return
    }
    setShow(false)
    modal.confirm({
      title: t['setting.title'],
      icon: <InfoCircleFilled style={{ color: '#44C5E4' }} />,
      className: cs(styles['custom-modal'], lang === 'en-US' ? '' : styles['custom-modal-rtl']),
      closable: true,
      content: t['setting.content'],
      okText: t['setting.ok'],
      cancelText: t['cancel'],
      keyboard: false,
      centered: true,
      width: 425,
      onOk() {
        window.electron?.ipcRenderer.openSetting('camera')
      },
    })
  }

  return (
    <>
      <CSSTransition in={show} classNames={'fade'} timeout={300} unmountOnExit>
        <>
          {mode === 'camera' && <Camera onCamera={onSubmit} back={close}></Camera>}
          {mode === 'choose' && (
            <div className={cs(styles['page'])}>
              <div>
                <div className={styles['choose']}>
                  <Button className={styles['choose-item']} type="text" onClick={onCamera}>
                    {t['takePhoto']}
                  </Button>
                  <Button className={styles['choose-item']} type="text" onClick={chooseFile}>
                    {t['chooseExisting']}
                  </Button>
                </div>
                <div className={styles['choose']} onClick={close}>
                  <Button className={styles['choose-item']} type="text">
                    {t['cancel']}
                  </Button>
                </div>
              </div>
            </div>
          )}
        </>
      </CSSTransition>
    </>
  )
}
export default forwardRef(UploadFile)

/**
 * const uploadRef = useRef(null)
 * comst [file,setFile]=useState<{parh:string;name:string}>(null)
 * uploadRef.current.open()
 * <UploadFile ref={uploadRef} onFile={}/>
 */
